let express = require('express');
let router = express.Router();

let Product = require('../models/product');

function productList() {
	// product
}

// 该路由使用的中间件
router.use(function timeLog(req, res, next) {
	next();
});
function jsonData(code,d) {
	return ( {error_code:code,data:d });
}
function formatDateTime(timestamp){
	let date = new Date(timestamp);
	let Y = date.getFullYear() + '-';
	let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
	let D = date.getDate() + ' ';
	let h = date.getHours() + ':';
	let m = date.getMinutes() + ':';
	let s = date.getSeconds();
	return Y+M+D+h+m+s;
}
/*路由控制*/
router.all('/create', function(req, res, next) {
	res.json(product.create());
});

router.get('/', function(req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	res.header('Access-Control-Allow-Headers', 'Content-Type');
	let json = {};
	json.type = req.query.type || '1,2,3';
	json.sort = req.query.sort || 'ASC';
	json.orderBy = req.query.orderBy || 'id';
	json.start = req.query.start || '0';
	json.limit = req.query.limit || '3';
	json.ids = req.query.ids || null;
	console.log('json====',json);
	Product.list(json,function (d) {
		d.map((v,k)=>{
			d[k].create_date = formatDateTime(d[k].create_date);
		});
		res.json(jsonData(0,d));
	});
});
router.get('/:name', function(req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	res.header('Access-Control-Allow-Headers', 'Content-Type');
	let id = req.params.name;
	Product.detail(id,function (d) {
		res.json(jsonData(0,d[0]));
	});
});

module.exports = router;
